#include "MdiChild.h"

MdiChild::MdiChild(QWidget *parent)
    : QWidget(parent)
{
    m_timer = new QTimer;
    m_timer->setInterval(10);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeSendData()));
}

MdiChild::~MdiChild()
{
    if(m_timer != NULL)
    {
        m_timer->stop();
        m_timer->deleteLater();
    }

    if(m_tcpclient != NULL)
    {
        m_tcpclient->abort();
        m_tcpclient->deleteLater();
    }
}
void MdiChild::onTimeSendData()
{
    SendData();
}
void MdiChild::clientWidget(QVBoxLayout *playout)
{
    QRegExp regExp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    QGroupBox* pGrpboxLocal = new QGroupBox(tr("Tcp"));
    QLabel *localhostLabel = new QLabel(pGrpboxLocal);
    localhostLabel->setText(tr("&IP:"));
    QLabel *localportLabel = new QLabel(pGrpboxLocal);
    localportLabel->setText(tr("&Port:"));
    localhostLineEdit = new QLineEdit(pGrpboxLocal);
    localhostLineEdit->setValidator(new QRegExpValidator(regExp, this));
    localportLineEdit = new QLineEdit(pGrpboxLocal);
    localportLineEdit->setValidator(new QIntValidator(1, 65535, this));
    localportLineEdit->setText("1883");
    localhostLabel->setBuddy(localhostLineEdit);
    localportLabel->setBuddy(localportLineEdit);
    pConn = new QPushButton(tr("Connect"));
    pConn->setDefault(true);
    pStop = new QPushButton(tr("Stop"));
    pStop->setDefault(true);
    pStop->setEnabled(false);
    QHBoxLayout *pVlocalnetcfg = new QHBoxLayout;
    pVlocalnetcfg->addWidget(localhostLabel);
    pVlocalnetcfg->addWidget(localhostLineEdit);
    pVlocalnetcfg->addWidget(localportLabel);
    pVlocalnetcfg->addWidget(localportLineEdit);
    QHBoxLayout *pHlayout = new QHBoxLayout;
    pHlayout->addWidget(pConn);
    pHlayout->addWidget(pStop);
    QHBoxLayout *pVlayout = new QHBoxLayout;
    pVlayout->addLayout(pVlocalnetcfg);
    pVlayout->addLayout(pHlayout);
    pGrpboxLocal->setLayout(pVlayout);
    playout->addWidget(pGrpboxLocal);
    connect(pConn, SIGNAL(clicked()), this, SLOT(requestNewFortune()));
    connect(pStop, SIGNAL(clicked()), this, SLOT(closeclient()));
    m_tcpclient = new QTcpSocket;
    connect(m_tcpclient, SIGNAL(readyRead()), this, SLOT(readFortune()));
    connect(m_tcpclient, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
}
void MdiChild::readFortune()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    QByteArray ba = socket->readAll();
    RecvData(ba.data(), ba.size());
}
void MdiChild::closeclient()
{
    m_tcpclient->close();
    m_timer->stop();
    pConn->setEnabled(true);
    pStop->setEnabled(false);
}
void MdiChild::requestNewFortune()
{
    if(!localhostLineEdit->text().isEmpty() &&
            !localhostLineEdit->text().isEmpty())
    {
        pStop->setEnabled(true);
        m_tcpclient->abort();
        m_tcpclient->connectToHost(localhostLineEdit->text(),
                                   localportLineEdit->text().toInt());
        pConn->setEnabled(false);
        m_timer->start();
    }
}
void MdiChild::displayError(QAbstractSocket::SocketError socketError)
{
    QString displayerr = "";

    switch(socketError)
    {
        case QAbstractSocket::RemoteHostClosedError:
            break;

        case QAbstractSocket::HostNotFoundError:
            displayerr = tr("The host was not found. Please check the host and port settings");
            QMessageBox::information(this, tr("Client"), displayerr);
            break;

        case QAbstractSocket::ConnectionRefusedError:
            displayerr = tr("The connection was refused by the peer.Make sure the server is running,and check that the host name and port settings are correct.");
            QMessageBox::information(this, tr("Client"), displayerr);
            break;

        default:
            displayerr = tr("The following error occurred: %1.")
                         .arg(m_tcpclient->errorString());
            QMessageBox::information(this, tr("Client"), displayerr);
    }

    m_timer->stop();
    pConn->setEnabled(true);
    pStop->setEnabled(false);
}
void MdiChild::SendData0(char* buf, int len)
{
    m_tcpclient->write(buf, len);
}
void MdiChild::RecvData(char* buf, int len)
{
    QString str = "recv:";

    for(int ii = 0; ii < len; ii++)
    {
        str.append(QString("%1 ").arg(buf[ii] & 0xFF, 2, 16, QChar('0')));
    }

    qDebug("%s", str.toStdString().c_str());
}